
package uit.qlks.from;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.rowset.WebRowSet;
import javax.sql.rowset.WebRowSet;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import uit.ejb.dto.UserDTO;
import uit.qlks.baocao.BaoCao;
import uit.qlks.controller.user.UserController;

/**
 *
 * @author SVN - Team
 */
public class frmQuanlynguoidung extends javax.swing.JFrame {

    /**
     * Creates new form Quanlynguoidung
     */
    public UserDTO _us = new UserDTO();
    public int x = 0;

    public frmQuanlynguoidung() {
        initComponents();
        this.setResizable(false);
        //this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    }
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnCapNhat = new javax.swing.JButton();
        btnThem = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbDSnguoidung = new javax.swing.JTable();
        btnXoa = new javax.swing.JButton();
        btnPrint = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("QUẢN LÝ NGƯỜI DÙNG");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        btnCapNhat.setFont(new java.awt.Font("Times New Roman", 0, 16)); // NOI18N
        btnCapNhat.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Edit.png"))); // NOI18N
        btnCapNhat.setText("Sửa");
        btnCapNhat.setBorder(null);
        btnCapNhat.setContentAreaFilled(false);
        btnCapNhat.setEnabled(false);
        btnCapNhat.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Edit2.png"))); // NOI18N
        btnCapNhat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCapNhatActionPerformed(evt);
            }
        });

        btnThem.setFont(new java.awt.Font("Times New Roman", 0, 16));
        btnThem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Add.png"))); // NOI18N
        btnThem.setText("Thêm");
        btnThem.setBorder(null);
        btnThem.setContentAreaFilled(false);
        btnThem.setEnabled(false);
        btnThem.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Add2.png"))); // NOI18N
        btnThem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThemActionPerformed(evt);
            }
        });

        tbDSnguoidung.setFont(new java.awt.Font("Times New Roman", 0, 16));
        tbDSnguoidung.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Tài khoản", "Tên người dùng", "Mật khẩu", "Quyền"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbDSnguoidung.getTableHeader().setReorderingAllowed(false);
        tbDSnguoidung.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbDSnguoidungMouseClicked(evt);
            }
        });
        tbDSnguoidung.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tbDSnguoidungKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(tbDSnguoidung);

        btnXoa.setFont(new java.awt.Font("Times New Roman", 0, 16));
        btnXoa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Delete.png"))); // NOI18N
        btnXoa.setText("Xóa");
        btnXoa.setBorder(null);
        btnXoa.setContentAreaFilled(false);
        btnXoa.setEnabled(false);
        btnXoa.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Delete2.png"))); // NOI18N
        btnXoa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXoaActionPerformed(evt);
            }
        });

        btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Printer.png"))); // NOI18N
        btnPrint.setText("Print");
        btnPrint.setBorder(null);
        btnPrint.setContentAreaFilled(false);
        btnPrint.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Printer2.png"))); // NOI18N
        btnPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrintActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addComponent(btnThem)
                        .addGap(57, 57, 57)
                        .addComponent(btnXoa)
                        .addGap(58, 58, 58)
                        .addComponent(btnCapNhat)
                        .addGap(47, 47, 47)
                        .addComponent(btnPrint)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnPrint)
                        .addComponent(btnCapNhat))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnThem)
                        .addComponent(btnXoa)))
                .addGap(11, 11, 11)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(22, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-496)/2, (screenSize.height-301)/2, 496, 301);
    }// </editor-fold>//GEN-END:initComponents

private void btnCapNhatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCapNhatActionPerformed
// TODO add your handling code here:
    frmNguoidung frm=new frmNguoidung(this,1);
    frm.setVisible(true);
    frm.setFocusable(true);
    this.setVisible(false);
}//GEN-LAST:event_btnCapNhatActionPerformed

private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
// TODO add your handling code here:
//    if(frmLogin._us.Role>0)
    btnThem.setEnabled(true);
    try {
        WebRowSet wrs = UserController.user_GetByAll();
        Object data[] = new Object[4];
        tbDSnguoidung.setToolTipText("Danh sách người dùng");
        DefaultTableModel model = (DefaultTableModel) tbDSnguoidung.getModel();
        while (model.getRowCount() > 0) {
            model.removeRow(0);
        }
        while (wrs.next()) {
            int role=Integer.parseInt(frmLogin._frm._us.getRole());
             if((role == 1 && !"2".equals(wrs.getString("Role"))) || role == 2)//neu là nhan vien thi khong duoc quan ly admin
            {
                if (wrs.getString("UserName") != null) {
                    data[0] = wrs.getString("UserName").trim();
                } else {
                    data[0] = wrs.getString("UserName");
                }
                if (wrs.getString("FullName") != null) {
                    data[1] = wrs.getString("FullName").trim();
                } else {
                    data[1] = wrs.getString("FullName");
                }
                if (wrs.getString("Password") != null) {
                    data[2] = wrs.getString("Password");
                } else {
                    data[2] = wrs.getString("Password");
                }
                String temp = "";
                if (wrs.getInt("Role") == 0) {
                    temp = "Người dùng";
                }
                if (wrs.getInt("Role") == 1) {
                    temp = "Nhân viên";
                }
                if (wrs.getInt("Role") == 2) {
                    temp = "Quản trị";
                }
                data[3] = temp;
                model.addRow(data);
            }
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage(), "Thông báo", JOptionPane.ERROR_MESSAGE);
    }
}//GEN-LAST:event_formComponentShown

private void tbDSnguoidungMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbDSnguoidungMouseClicked
//// TODO add your handling code here:
    if(Integer.parseInt(frmLogin._us.getRole())>0)
        btnCapNhat.setEnabled(true);
    if(Integer.parseInt(frmLogin._us.getRole())>1)
        btnXoa.setEnabled(true);
    //thong tin nguoi dung dang duoc
    int sel_row=tbDSnguoidung.getSelectedRow();
    _us.setUserName(tbDSnguoidung.getValueAt(sel_row,0).toString());
    _us.setFullName(tbDSnguoidung.getValueAt(sel_row,1).toString());
    _us.setPassword(tbDSnguoidung.getValueAt(sel_row,2).toString());
     String temp=tbDSnguoidung.getValueAt(sel_row,3).toString();
    if(temp.equals("Người dùng"))
        _us.setRole("0");
    else if(temp.equals("Quản trị"))
        _us.setRole("2");
    else _us.setRole("1");
    try
    {
        WebRowSet wrs=UserController.user_GetById(_us);
        wrs.next();
       _us.setId(wrs.getObject("Id").toString());
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(new JFrame(), "Đường truyền bị gián đoạn ! Xin vui lòng kiểm tra lại", "Test Connect", JOptionPane.INFORMATION_MESSAGE);
    }
}//GEN-LAST:event_tbDSnguoidungMouseClicked

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
// TODO add your handling code here:
    frmMain._main.setVisible(true);
    frmMain._main.setFocusable(true);
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}//GEN-LAST:event_formWindowClosed

private void tbDSnguoidungKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbDSnguoidungKeyTyped
// TODO add your handling code here:
    // if(evt.getKeyChar()=='\n')
}//GEN-LAST:event_tbDSnguoidungKeyTyped

private void btnThemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemActionPerformed
// TODO add your handling code here:
        frmNguoidung frm = new frmNguoidung(this,0);
        frm.setVisible(true);
        frm.setFocusable(true);
        this.setVisible(false);
}//GEN-LAST:event_btnThemActionPerformed

private void btnXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaActionPerformed
// TODO add your handling code here:
    if(btnXoa.isEnabled())
    {
        if(frmLogin._us.getUserName().equals(_us.getUserName())){
            JOptionPane.showMessageDialog(this, "Bạn không thể xóa người dùng hiện tại", "Thông báo", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int result= JOptionPane.showConfirmDialog(this, "Bạn có chắc chắn xóa người dùng không?","Thông báo",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
        if(result ==JOptionPane.YES_OPTION){
            try
            {
                if(UserController.user_Delete(_us.getId())!=0){
                    JOptionPane.showMessageDialog(this, "Xóa người dùng thành công", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
                    DefaultTableModel model = (DefaultTableModel)tbDSnguoidung.getModel();
                    model.removeRow(tbDSnguoidung.getSelectedRow());
                }
                else JOptionPane.showMessageDialog(this, "Không thể xóa người dùng", "Thông báo", JOptionPane.ERROR_MESSAGE);
            }
            catch(Exception e)
            {
               JOptionPane.showMessageDialog(new JFrame(), "Đường truyền bị gián đoạn ! Xin vui lòng kiểm tra lại", "Test Connect", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
}//GEN-LAST:event_btnXoaActionPerformed

private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed
    try {
            // TODO add your handling code here:
            String html1 = "";
            html1 += "<CENTER><h2>DANH SÁCH TÀI KHOẢN NHÂN VIÊN</h2>";
            String footer ="";
            BaoCao bc = new BaoCao();
            bc.baocao(tbDSnguoidung,html1,footer,"400");
        } catch (Exception ex) {
            Logger.getLogger(frmBaoCao.class.getName()).log(Level.SEVERE, null, ex);
        }
    // TODO add your handling code here:
}//GEN-LAST:event_btnPrintActionPerformed

    /**
     * @param args the command line arguments
     */
 public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
 
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new frmQuanlynguoidung().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCapNhat;
    private javax.swing.JButton btnPrint;
    private javax.swing.JButton btnThem;
    private javax.swing.JButton btnXoa;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbDSnguoidung;
    // End of variables declaration//GEN-END:variables
}
